//
//  IMTextMessageTableViewCell.m
//  MLIM
//
//  Created by molon on 15/6/25.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "IMTextMessageTableViewCell.h"
#import "IMCommon.h"
#import "IMMessageBackgroundImageView.h"
#import "IMUserAvatarImageView.h"

#define MSG ((IMTextMessage*)self.imMessage)

//下面俩是label相对于背景图的边距
#define kContentLabelYMargin 10.0f
#define kContentLabelXMargin 10.0f
@interface IMTextMessageTableViewCell()

@property (nonatomic, strong) MLLinkLabel *contentLabel;

@end

@implementation IMTextMessageTableViewCell

- (void)resetWithIsInit:(BOOL)isInit
{
    [super resetWithIsInit:isInit];
    
    if (isInit) {
        [self.backgroundImageView addSubview:self.contentLabel];
    }
}

#pragma mark - getter
- (MLLinkLabel *)contentLabel
{
    if (!_contentLabel) {
        _contentLabel = [MLLinkLabel new];
        _contentLabel.numberOfLines = 0;
        _contentLabel.font = [UIFont systemFontOfSize:16.0f];
        _contentLabel.dataDetectorTypes = MLDataDetectorTypeURL|MLDataDetectorTypePhoneNumber|MLDataDetectorTypeEmail|MLDataDetectorTypeAttributedLink;
        
        _contentLabel.backgroundColor = [UIColor clearColor];
        _contentLabel.textColor = [UIColor blackColor];
        
        WEAKSELF
        [_contentLabel setDidClickLinkBlock:^(MLLink *link, NSString *linkText, MLLinkLabel *label) {
            STRONGSELF
            
            NSString *linkValue = link.linkValue;
            NSString *url = nil;
            switch(link.linkType){
                case MLLinkTypeURL:
                    if ([[linkValue lowercaseString] hasPrefix:@"www."]) {
                        linkValue = [@"http://" stringByAppendingString:linkValue];
                    }
                    if (sSelf.didClickLinkURLBlock) {
                        sSelf.didClickLinkURLBlock([NSURL URLWithString:linkValue]);
                        return;
                    }
                    url = linkValue;
                    break;
                case MLLinkTypePhoneNumber:
                    url = [NSString stringWithFormat:@"telprompt://%@",[linkValue normalizedPhoneNumber]];
                    break;
                case MLLinkTypeEmail:
                    url = [NSString stringWithFormat:@"mailto://%@",linkValue];
                    break;
                default:
                    DLOG(@"点击了不知道啥%@",link);
                    break;
            }
            if (![NSString IsNilOrEmpty:url]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            }
        }];
    }
    return _contentLabel;
}

#pragma mark - setter
- (void)setImMessage:(IMMessage *)imMessage
{
    NSAssert(!imMessage||[imMessage isKindOfClass:[IMTextMessage class]], @"只能传递进来Text消息");
    [super setImMessage:imMessage];
    
    self.contentLabel.text = MSG.content;
    
    self.contentLabel.textColor = IMISME(imMessage.clientId)?IMCONFIGM.senderTextColor:IMCONFIGM.recevierTextColor;
    
    [self setNeedsLayout];
}

#pragma mark - height

static MLLinkLabel * kProtypeContentLabel() {
    static MLLinkLabel *_protypeContentLabel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        MLLinkLabel *contentLabel = [MLLinkLabel new];
        contentLabel.numberOfLines = 0;
        contentLabel.font = [UIFont systemFontOfSize:16.0f];
        contentLabel.dataDetectorTypes = MLDataDetectorTypeURL|MLDataDetectorTypePhoneNumber|MLDataDetectorTypeEmail|MLDataDetectorTypeAttributedLink;
        
        _protypeContentLabel = contentLabel;
    });
    
    return _protypeContentLabel;
}

+ (CGFloat)heightOfMessage:(IMMessage*)imMessage maxWidth:(CGFloat)maxWidth
{
    MLLinkLabel *contentLabel = kProtypeContentLabel();
    contentLabel.text = ((IMTextMessage*)imMessage).content;
    
    CGFloat labelMaxWidth = maxWidth*kMaxWidthRadioOfBackImageView-kContentLabelXMargin*2-IMCONFIGM.messageBackgroundArrowWidth;
    
    CGFloat height = [contentLabel preferredSizeWithMaxWidth:labelMaxWidth].height+kContentLabelYMargin*2+kIMMessageCellBottomPadding;
    height = MAX(height, kMinMessageCellHeight);
    
    if (imMessage.displayDate) {
        return height+kDateLabelHeight+kDateLabelYMargin*2;
    }
    
    return height;
}


#pragma mark - layout
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat labelMaxWidth = self.contentView.frameWidth*kMaxWidthRadioOfBackImageView-kContentLabelXMargin*2-IMCONFIGM.messageBackgroundArrowWidth;
    
    //TODO:这里不太好，应该从下往上自然的推出来位置，而不是需要再次计算
    CGSize sizeOfContentLabel = [self.contentLabel preferredSizeWithMaxWidth:labelMaxWidth];
    
    CGFloat backImageViewWidth = sizeOfContentLabel.width+kContentLabelXMargin*2+IMCONFIGM.messageBackgroundArrowWidth;
    
    CGFloat backImageViewHeight = MAX(sizeOfContentLabel.height+kContentLabelYMargin*2, kAvatarImageViewSideLength);
    
    //左和右
    if (IMISME(self.imMessage.clientId)) {
        self.backgroundImageView.frame = CGRectMake(self.avatarImageView.frameX - kElementXSpacing/2 - backImageViewWidth, self.avatarImageView.frameY, backImageViewWidth, backImageViewHeight);
        
        self.contentLabel.frame = CGRectMake(kContentLabelXMargin, (backImageViewHeight-sizeOfContentLabel.height)/2, sizeOfContentLabel.width, sizeOfContentLabel.height);
    }else{
        self.backgroundImageView.frame = CGRectMake(self.avatarImageView.frameRight + kElementXSpacing/2, self.avatarImageView.frameY, backImageViewWidth, backImageViewHeight);
        
        self.contentLabel.frame = CGRectMake(kContentLabelXMargin+IMCONFIGM.messageBackgroundArrowWidth, (backImageViewHeight-sizeOfContentLabel.height)/2, sizeOfContentLabel.width, sizeOfContentLabel.height);
    }
    
    [self layoutEnd];
}
@end
